package edu.fiu.cis.nursing.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import edu.fiu.cis.nursing.shared.UserToken;

public class LoginWindow extends Composite {
	TextBox userName;
	PasswordTextBox password;

	public LoginWindow(final NursingServiceAsync service, final Nursing nursing) {
		userName = new TextBox();
		password = new PasswordTextBox();

		VerticalPanel panel = new VerticalPanel();
		panel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);

		panel.add(new LoginText("Email:", userName));
		panel.add(new LoginText("Password:", password));

		SubmitButton sb = new SubmitButton("Login");
		panel.add(sb);
		sb.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				service.loginUser(userName.getText(), password.getText(),
						new DefaultAsyncCallback<UserToken>() {

							@Override
							public void onSuccess(UserToken result) {
								if (result != null) {
									Cookies.setCookie(
											Nursing.NURSING_COOKIE_NAME,
											result.getCookie());
									nursing.performInteractiveFlow();
								} else {
									RootPanel.get("errorLabelContainer")
											.clear();
									RootPanel.get("errorLabelContainer").add(
											new HTML("Login Unsuccessful"));
								}
							}
						});

			}
		});

		initWidget(panel);
	}

	static class LoginText extends Composite {
		public LoginText(String text, TextBox box) {

			HorizontalPanel p = new HorizontalPanel();
			p.setWidth("200px");

			HTML h = new HTML(text);
			h.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);

			p.add(h);
			p.add(box);

			initWidget(p);
		}
	}

}
